Python TXT to CSV Tutorial | Convert TXT Files to CSV in Python

Python TXT to CSV Tutorial | Convert TXT Files to CSV in Python

2025-10-15 07:42:33 Written by  zaki zou
Rate this item
(0 votes)

Python TXT to CSV Conversion Guide

When working with data in Python, converting TXT files to CSV is a common and essential task for data analysis, reporting, or sharing data between applications. TXT files often store unstructured plain text, which can be difficult to process, while CSV files organize data into rows and columns, making it easier to work with and prepare for analysis. This tutorial explains how to convert TXT to CSV in Python efficiently, covering single-file conversion, batch conversion, and tips for handling different delimiters.

Table of Contents

What is a CSV File?

A CSV (Comma-Separated Values) file is a simple text-based file format used to store tabular data. Each line in a CSV file represents a row, and values within the row are separated by commas (or another delimiter such as tabs or semicolons).

CSV is widely supported by spreadsheet applications, databases, and programming languages like Python. Its simple format makes it easy to import, export, and use across platforms such as Excel, Google Sheets, R, and SQL for data analysis and automation.

An Example CSV File:

Name, Age, City

John, 28, New York

Alice, 34, Los Angeles

Bob, 25, Chicago

Python TXT to CSV Library - Installation

To perform TXT to CSV conversion in Python, we will use Spire.XLS for Python, a powerful library for creating and manipulating Excel and CSV files, without requiring Microsoft Excel to be installed.

Python TXT to CSV Converter

You can install it directly from PyPI with the following command:

pip install Spire.XLS

If you need instructions for the installation, visit the guide on How to Install Spire.XLS for Python.

Convert a TXT File to CSV in Python (Step-by-Step)

Converting a text file to CSV in Python is straightforward. You can complete the task in just a few steps. Below is a basic outline of the process:

  • Prepare and read the text file: Load your TXT file and read its content line by line.
  • Split the text data: Separate each line into fields using a specific delimiter such as a space, tab, or comma.
  • Write data to CSV: Use Spire.XLS to write the processed data into a new CSV file.
  • Verify the output: Check the CSV in Excel, Google Sheets, or a text editor.

The following code demonstrates how to export a TXT file to CSV using Python:

from spire.xls import *

# Read the txt file
with open("data.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()

# Process each line by splitting based on spaces (you can change the delimiter if needed)
processed_data = [line.strip().split() for line in lines]

# Create an Excel workbook
workbook = Workbook()
# Get the first worksheet
sheet = workbook.Worksheets[0]

# Write data from the processed list to the worksheet
for row_num, row_data in enumerate(processed_data):
    for col_num, cell_data in enumerate(row_data):
        # Write data into cells
        sheet.Range[row_num + 1, col_num + 1].Value = cell_data

# Save the sheet as CSV file (UTF-8 encoded)
sheet.SaveToFile("TxtToCsv.csv", ",", Encoding.get_UTF8())
# Dispose the workbook to release resources
workbook.Dispose()

TXT to CSV Output:

Python Convert TXT to CSV using Spire.XLS

If you are also interested in converting a TXT file to Excel, see the guide on converting TXT to Excel in Python.

Automate Batch Conversion of Multiple TXT Files

If you have multiple text files that you want to convert to CSV automatically, you can loop through all .txt files in a folder and convert them one by one.

The following code demonstrates how to batch convert multiple TXT files to CSV in Python:

import os
from spire.xls import *

# Folder containing TXT files
input_folder = "txt_files"
output_folder = "csv_files"

# Create output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)

# Function to process a single TXT file
def convert_txt_to_csv(file_path, output_path):
    # Read the TXT file
    with open(file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()
    
    # Process each line (split by space, modify if your delimiter is different)
    processed_data = [line.strip().split() for line in lines if line.strip()]
    
    # Create workbook and access the first worksheet
    workbook = Workbook()
    sheet = workbook.Worksheets[0]
    
    # Write processed data into the sheet
    for row_num, row_data in enumerate(processed_data):
        for col_num, cell_data in enumerate(row_data):
            sheet.Range[row_num + 1, col_num + 1].Value = cell_data
    
    # Save the sheet as CSV with UTF-8 encoding
    sheet.SaveToFile(output_path, ",", Encoding.get_UTF8())
    workbook.Dispose()
    print(f"Converted '{file_path}' -> '{output_path}'")

# Loop through all TXT files in the folder and convert each to a CSV file with the same file name
for filename in os.listdir(input_folder):
    if filename.lower().endswith(".txt"):
        input_path = os.path.join(input_folder, filename)
        output_name = os.path.splitext(filename)[0] + ".csv"
        output_path = os.path.join(output_folder, output_name)
        
        convert_txt_to_csv(input_path, output_path)

Advanced Tips for Python TXT to CSV Conversion

Converting text files to CSV can involve variations in text file layout and potential errors, so these tips will help you handle different scenarios more effectively.

1. Handle Different Delimiters

Not all text files use spaces to separate values. If your TXT file uses tabs, commas, or other characters, you can adjust the split() function to match the delimiter.

  • For tab-separated files (.tsv):
processed_data = [line.strip().split('\t') for line in lines]
  • For comma-separated files:
processed_data = [line.strip().split(',') for line in lines]
  • For custom delimiters (e.g., |):
processed_data = [line.strip().split('|') for line in lines]

This ensures that your data is correctly split into columns before writing to CSV.

2. Add Error Handling

When reading or writing files, it's a good practice to use try-except blocks to catch potential errors. This makes your script more robust and prevents unexpected crashes.

try:
    # your code here
except Exception as e:
print("Error:", e)

Tip: Use descriptive error messages to help understand the problem.

  1. Skip Empty Lines
    Sometimes, text files may have empty lines. You can filter out the blank lines to avoid creating empty rows in CSV:
processed_data = [line.strip().split() for line in lines if line.strip()]

Conclusion

In this article, you learned how to convert a TXT file to CSV format in Python using Spire.XLS for Python. This conversion is an essential step in data preparation, helping organize raw text into a structured format suitable for analysis, reporting, and sharing. With Spire.XLS for Python, you can automate the text to CSV conversion, handle different delimiters, and efficiently manage multiple text files.

If you have any questions or need technical assistance about Python TXT to CSV conversion, visit our Support Forum for help.

FAQs: Python Text to CSV

Q1: Can I convert TXT files to CSV without Microsoft Excel installed?

A1: Yes. Spire.XLS for Python works independently of Microsoft Excel, allowing you to create and export CSV files directly.

Q2: How to batch convert multiple TXT files to CSV in Python?

A2: Use a loop to read all TXT files in a folder and apply the conversion function for each. The tutorial includes a ready-to-use Python example for batch conversion.

Q3: How do I handle empty lines or inconsistent rows in TXT files when converting to CSV?

A3: Filter out empty lines during processing and implement checks for consistent column counts to avoid errors or blank rows in the output CSV.

Q4: How do I convert TXT files with tabs or custom delimiters to CSV in Python?

A4: You can adjust the split() function in your Python script to match the delimiter in your TXT file-tabs (\t), commas, or custom characters-before writing to CSV.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 15 October 2025 07:43